package test3.dao.impl;

import test3.bean.Admini;
import test3.dao.AdminiDao;
import test3.file.FileModel;

import java.util.HashMap;
/**
 * 这是一个单例的AdminiDaoImpl，这意味着在内存中只可能出现最多一个AdminiDaoImpl对象
 */
public class AdminiDaoImpl implements AdminiDao{

    /**
     * 在内存中仅有一个AdminiDaoImpl对象
     */
    private static AdminiDaoImpl adminiDao=new AdminiDaoImpl();

    private FileModel model;

    private HashMap<String,String> adminis;

    private AdminiDaoImpl(){
        model=new FileModel();
        adminis=model.getAdministrators();
    }

    public static AdminiDaoImpl createAdminiDaoImpl(){
        if (adminiDao==null)
            adminiDao=new AdminiDaoImpl();
        return adminiDao;
    }

    @Override
    public HashMap<String, String> getAllAdminis() {
        return adminis;
    }

    @Override
    public void addAdmini(Admini admini) {
        adminis.put(admini.getUsername(),admini.getPassword());
        model.saveAdministrators(adminis);
    }

    @Override
    public boolean loginAdmini(Admini admini) {
        boolean flag=false;

        if(adminis==null || adminis.size()==0)
            return true;

        if (admini.getUsername()==null || admini.getPassword()==null ||
                admini.getPassword().equals("") || admini.getUsername().equals(""))
            return false;

        for (int i=0;i<adminis.size();i++){
            String value=adminis.get(admini.getUsername());
            if (value!=null) {
                if (value.equals(admini.getPassword())) {
                    flag = true;
                    return flag;
                }
            }
            else
                return flag;
        }
        return flag;
    }
}
